package com.zjdiepu.www.biz.partner;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.diepu.www.client.xhh.partner.request.QueryStatusRequest;
import com.diepu.www.client.xhh.partner.response.QueryLoanResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.ThirdBusiStatus;
import com.zjdiepu.www.base.enums.status.ThirdHandleStatus;
import com.zjdiepu.www.base.enums.status.ThirdLogEventStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.ThirdModeIDType;
import com.zjdiepu.www.consts.XhhService;
import com.zjdiepu.www.dao.partner.ThBusinessRecordMapper;
import com.zjdiepu.www.dao.partner.ThLendingMapper;
import com.zjdiepu.www.dao.partner.ThYwBusinessMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.partner.IThHandleErrService;
import com.zjdiepu.www.ibiz.partner.IThLendingService;
import com.zjdiepu.www.ibiz.partner.IThLogsService;
import com.zjdiepu.www.ibiz.partner.IThYwBusinessService;
import com.zjdiepu.www.model.partner.dto.ThBusinessRecord;
import com.zjdiepu.www.model.partner.dto.ThLending;
import com.zjdiepu.www.model.partner.dto.ThYwBusiness;
import com.zjdiepu.www.model.partner.ext.ThLendingExt;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.security.exception.BasePartnerException;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.xhh.XinHeHuiClient;

/**
 * 第三方放款信息Service层操作实现<br/>
 * @author zhangzhengjian<br/>
 * @time 2017年09月25日 14时01分<br/>
 * @since 1.0<br/>
 */
@Service
public class ThLendingServiceImpl extends BaseService implements IThLendingService {
	public static final Logger logger = LoggerFactory.getLogger(ThLendingServiceImpl.class);

	@Autowired
	private ThLendingMapper thLendingMapper;
	
	@Autowired
	private ThYwBusinessMapper thYwBusinessMapper;
	@Autowired
	private IThHandleErrService thHandleErrService;
	@Autowired
	private ThBusinessRecordMapper thBusinessRecordMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	
	@Autowired
	private IThYwBusinessService thYwBusinessService;
	@Autowired
	private IThLogsService thLogsService;
	
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public boolean saveApplyXinHeHuiLending(String busiId, 
			String currentUserId, String currentUserName) {
		if(StringUtils.isBlank(busiId)) { //业务ID无，不需要记录错误处理（没意义）
			ExceptionHelper.thow("999", "业务记录ID不能为空");
		}
		QueryStatusRequest queryStatusRequest = null;
		
		String preRequestUrl = null;
		Map<String, String> preRequestParam = null;
		String xeApplyNo=null;
		String thired="";
		String busiType = "xhh";
		try {
			queryStatusRequest = new QueryStatusRequest();
			
			ThYwBusiness thYwBusiness= new ThYwBusiness();
			thYwBusiness.setBusiId(busiId);
			ThYwBusiness thYw=thYwBusinessMapper.selectRefined(thYwBusiness);
			if(thYw!=null){
				thired=thYw.getThirdId();
				queryStatusRequest.setXeApplyNo(thired);
			}
			
			preRequestUrl = XinHeHuiClient.preRequestUrl(XhhService.QUERY_LOAN);
			preRequestParam = XinHeHuiClient.preRequestParam(queryStatusRequest);
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thired, busiType, xeApplyNo, 
					queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
							preRequestUrl, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.QUERY_LOAN_DES, ThirdModeIDType.FKCX,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thired, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FA_SONG_SHI_BAI, null, ThirdModeIDType.FKCX, 
					currentUserId, currentUserName, new Date());
			return false;
		}
//		==========================请求前:开始==================================
//		======================请求:开始===========================
		String requestJsonString = null;
		try {
			requestJsonString = XinHeHuiClient.request(preRequestUrl, preRequestParam);
			thLogsService.saveOrUpdateLog(busiId, thired, busiType, xeApplyNo, 
					queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
							requestJsonString, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.SUCCESS, XhhService.QUERY_LOAN_DES, ThirdModeIDType.FKCX,
					currentUserId, currentUserName);
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thired, busiType, xeApplyNo, 
					queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
							requestJsonString, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.QUERY_LOAN_DES, ThirdModeIDType.FKCX,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thired, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.FAN_HUI_SHI_BAI, null, ThirdModeIDType.FKCX, 
					currentUserId, currentUserName, new Date());
			return false;
		}
//		======================处理:开始===========================
		QueryLoanResponse queryLoanResponse = null;
		try{
			queryLoanResponse = XinHeHuiClient.parseResponse(requestJsonString, QueryLoanResponse.class);
			if(null == queryLoanResponse || StringUtils.isBlank(queryLoanResponse.getOrderSn())) {
				throw new BasePartnerException(999, "返回的数据或编号为空");
			}
			//第三方信息履历表
//			ThBusinessRecord thBusinessRecord=new ThBusinessRecord();
//			thBusinessRecord.setBusiId(busiId);
////			============@update 缺关键条件 xiongxiaotun 2017-11-27 18:09
//			thBusinessRecord.setDpStatus(DpStatus.NORMAL.getCode());
//			thBusinessRecord.setOrderSql(" CREATED DESC ");
//			thBusinessRecord.setThirdModeId(ThirdModeIDType.FKCX.getCode());
//			ThBusinessRecord ThBusinessRecord1=thBusinessRecordMapper.selectRefined(thBusinessRecord);
			
			//放款信息表			
			ThLending thLending1=new ThLending();
			thLending1.setBusiId(busiId);
			ThLending thLending2=thLendingMapper.selectRefined(thLending1);
			
			ThYwBusiness thYwBusiness= new ThYwBusiness();
			thYwBusiness.setBusiId(busiId);
			thYwBusiness=thYwBusinessMapper.selectRefined(thYwBusiness);
			
			//业务信息表
			YwBusiness ywBusiness= new YwBusiness();
			ywBusiness.setId(busiId);
			ywBusiness=ywBusinessMapper.selectRefined(ywBusiness);
			xeApplyNo = queryLoanResponse.getOrderSn();
			String lendingStatusName=""	;
			Integer lendingStatus=0;
			if(thLending2==null){
				ThLending thlending= new ThLending();
				thlending.setBusiId(busiId);
				thlending.setThirdId(thired);
				if(queryLoanResponse.getLoanStatus()!=null){
					if(queryLoanResponse.getLoanStatus()==5){
						lendingStatusName="放款成功";
						lendingStatus=1;
						if(thYwBusiness!=null){
							thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
						}
						if(ywBusiness!=null){
							ywBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
						}
					}else{
						lendingStatusName="放款失败";
						lendingStatus=0;
						if(thYwBusiness!=null){
							thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_SHI_BAI.getCode());
						}
						if(ywBusiness!=null){
							ywBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_SHI_BAI.getCode());
						}
					}
				}
				thlending.setLendingStatusName(lendingStatusName);
				thlending.setLendingStatus(lendingStatus);
				thlending.setLoanBankName(queryLoanResponse.getLoanBankName());
				thlending.setLoanDate(queryLoanResponse.getLoanDate());
				thlending.setLoanCardNo(queryLoanResponse.getLoanCardNo());
				thlending.setLoanFee(BigDecimal.valueOf(queryLoanResponse.getLoanFee()));
				thlending.setBusiType(busiType);
				thlending.initInsertData(currentUserId, currentUserName);
				thLendingMapper.insert(thlending);
				
				ThBusinessRecord thBusinessRecordNew=new ThBusinessRecord();
				thBusinessRecordNew.setRecordEvent(lendingStatusName);
				thBusinessRecordNew.setDataId(thlending.getId());
				thBusinessRecordNew.setThirdId(thired);
				thBusinessRecordNew.setBusiId(busiId);
				thBusinessRecordNew.setBusiType(busiType);
				thBusinessRecordNew.setThirdModeId(ThirdModeIDType.FKCX.getCode());
				thBusinessRecordNew.setThirdModeName(ThirdModeIDType.FKCX.getValue());
				thBusinessRecordNew.initInsertData(currentUserId, currentUserName);
				thBusinessRecordMapper.insert(thBusinessRecordNew);
				
				
			}else{
				//如果第三方信息履历表中没有放款结果信息，或者最新的一条放款结果信息和当前返回的放款结果不一致，写入一条放款结果信息。履历描述为放款完成或者放款失败；
				if(thLending2.getLendingStatus() !=null &&!thLending2.getLendingStatus().equals(queryLoanResponse.getLoanStatus())){
					ThLending thlending= new ThLending();
					thlending.setBusiId(busiId);
					thlending.setThirdId(thired);
					if(queryLoanResponse.getLoanStatus()!=null){
						if(queryLoanResponse.getLoanStatus()==5){
							lendingStatusName="放款成功";
							lendingStatus=1;
							//第三方订单信息状态值失败
							if(thYwBusiness!=null){
								thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
							}
							if(ywBusiness!=null){
								ywBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
							}
						}else{
							lendingStatusName="放款失败";
							lendingStatus=0;
							if(thYwBusiness!=null){
								thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_SHI_BAI.getCode());
							}
							if(ywBusiness!=null){
								ywBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_SHI_BAI.getCode());
							}
						}
					}
					thlending.setLendingStatusName(lendingStatusName);
					thlending.setLendingStatus(lendingStatus);
					thlending.setLoanBankName(queryLoanResponse.getLoanBankName());
					thlending.setLoanCardNo(queryLoanResponse.getLoanCardNo());
					thlending.setLoanFee(BigDecimal.valueOf(queryLoanResponse.getLoanFee()));
					thlending.setBusiType(busiType);
					thlending.setLoanDate(queryLoanResponse.getLoanDate());
					thlending.initInsertData(currentUserId, currentUserName);
					thLendingMapper.insert(thlending);
				}else{
					if(thYwBusiness!=null){
						thYwBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
					}
					if(ywBusiness!=null){
						ywBusiness.setThirdBusiStatus(ThirdBusiStatus.FANG_KUAN_CHENG_GONG.getCode());
					}
				}
			}
			//更新第三方订单信息的【第三方渠道业务状态值】为‘放款完成’或者‘放款失败’
			thYwBusiness.initUpdateData(currentUserId, currentUserName);
			thYwBusinessMapper.updateByPrimaryKeySelective(thYwBusiness);
			
			
			//将yw_业务信息表的第三方渠道业务状态值更改为‘放款完成’或者‘放款失败’；
			ywBusiness.initUpdateData(currentUserId, currentUserName);
			ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
			
//			thLogsService.saveOrUpdateLog(busiId, thired, busiType, xeApplyNo, 
//					queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
//							requestJsonString, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
//							ThirdLogEventStatus.SUCCESS, XinHeHuiService.QUERY_LOAN_DES, ThirdModeIDType.FKCX,
//					currentUserId, currentUserName);
			return true;
		} catch (Exception e) {
			String[] ids = thLogsService.saveOrUpdateLog(busiId, thired, busiType, xeApplyNo, 
					queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEvent(), 
							requestJsonString, queryStatusRequest == null ? null : queryStatusRequest.getRequestMessageEventEncode(),
							ThirdLogEventStatus.FAIL, XhhService.QUERY_LOAN_DES, ThirdModeIDType.FKCX,
					currentUserId, currentUserName);
			String logId = (null != ids && ids.length >= 2) ? ids[0] : null;
			String logSubId = (null != ids && ids.length >= 2) ? ids[1] : null;
			thHandleErrService.saveOrUpdateThHandleErr(e, busiId, thired, logId, logSubId, busiType, 
					xeApplyNo, ThirdHandleStatus.CHU_LI_SHI_BAI, null, ThirdModeIDType.FKCX, 
					currentUserId, currentUserName, new Date());
			return false;
		}
	}
	
	@Override
	public void saveUpdateAndDelete(ThLending thLending, OperateType operType) {
		switch (operType) {
		case add:
			thLending.initInsertData(thLending.getModifier(), thLending.getModifierName());
			thLendingMapper.insert(thLending);
			break;
		case edit:
			thLending.initUpdateData(thLending.getModifier(), thLending.getModifierName());
			// 影响的记录数
			int updateCount = thLendingMapper.updateByPrimaryKeySelective(thLending);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			thLending.initDeleteData(thLending.getModifier(), thLending.getModifierName());
			// 影响的记录数
			int deleteCount = thLendingMapper.updateByPrimaryKeySelective(thLending);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<ThLending> selectByExt(ThLendingExt thLendingExt) {
		return thLendingMapper.selectByExt(thLendingExt);
	}
	
	@Override
	public int countByExt(ThLendingExt thLendingExt){
		return thLendingMapper.countByExt(thLendingExt);
	}
	
	@Override
	public ThLending selectById(String id) {
		return thLendingMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			thLendingMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(ThLending thLending) {
		return thLendingMapper.countRefined(thLending);
	}

	@Override
	public ThLending selectRefined(ThLending thLending) {
		return thLendingMapper.selectRefined(thLending);
	}

	@Override
	public boolean repeat(ThLending thLending) {
		int count = countRefined(thLending);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(thLending.getId())) {
			return true;
		}
		ThLending dbItem = selectRefined(thLending);
		if(null == dbItem) {
			return false;
		}
		return !thLending.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return thLendingMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
}
